import React, { useMemo } from 'react';
import ClassNames from 'classnames';
import { viewSizeFormat } from '@/common/format';

import styles from './style.scss';

const PlayLoading = ({
  className,
  number,
  align,
  width,
  height,
  itemWidth,
  itemHeight,
  itemMinHeight,
  color,
  animationPlayState,
}) => {
  const getItemHeight = (index) => {
    let heightFlag = itemHeight;
    const itemHeightType = typeof itemHeight;
    if (itemHeightType === 'undefined') {
      heightFlag = height;
    }

    if (itemHeightType === 'function') {
      heightFlag = itemHeight({ index });
    }

    return viewSizeFormat(heightFlag);
  };

  const getItemMinHeight = (index) => {
    let minHeightFlag = itemMinHeight;
    if (typeof itemMinHeight === 'function') {
      minHeightFlag = itemMinHeight({ index });
    }

    return viewSizeFormat(minHeightFlag);
  };

  const itemWidthVal = useMemo(() => viewSizeFormat(itemWidth), [itemWidth]);

  return (
    <div
      className={ClassNames(styles.container, className, {
        [styles.isTop]: align === 'top',
        [styles.isCenter]: align === 'center',
        [styles.isBottom]: align === 'bottom',
      })}
      style={{ width: `${width}px`, height: `${height}px` }}
    >
      {new Array(number).fill(0).map((row, index) => (
        <div
          className={styles.item}
          style={{
            width: `${itemWidthVal}px`,
            animationDelay: `${0.2 * index}s`,
            backgroundColor: color,
            borderRadius: `${itemWidthVal / 2}px`,
            height: `${getItemHeight(index)}px`,
            minHeight: `${getItemMinHeight(index)}px`,
            animationPlayState,
          }}
          key={index}
        />
      ))}
    </div>
  );
};

PlayLoading.defaultProps = {
  number: 4,
  align: 'bottom',
  width: 40,
  height: 40,
  itemWidth: 4,
  color: '#fff',
  itemMinHeight: 0,
  animationPlayState: 'running',
};

export default PlayLoading;
